<template>
  <div>
    <div class="personalInfo-header">
      <div class="function-title" v-text="functionTitle" />
      <div class="operat-box">
        <span v-if="!isMod">
          <el-button @click="modInfo">修改信息</el-button>
        </span>
        <span v-else>
          <el-button @click="isMod = false">取消</el-button>
          <el-button type="primary" @click="submit">确认</el-button>
        </span>
      </div>
    </div>

    <div class="updateinfo">
      <div class="update-form">
        <el-form :model="memberInfo" :rules="rules" ref="form" label-width="100px" :hide-required-asterisk="true">
          <el-form-item label="头像" prop="avatar">
            <el-upload
              v-if="isMod"
              class="avatar-uploader"
              action="http://120.48.118.48:8222/eduoss/fileoss/avatar"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="memberInfo.avatar"
                :src="memberInfo.avatar"
                class="avatar"
                style="height: 128px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <img v-else class="el-upload" style="height: 128px;width: 128px;" :src="member.avatar" />
          </el-form-item>
          <el-form-item v-if="isMod" label="密码">
            <el-input type="password" :show-password="true" v-model="memberInfo.password" />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <span v-if="isMod">
              <el-input v-if="isMod" v-model="memberInfo.nickname"/>
            </span>
            <span v-else v-text="member.nickname"></span>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <span v-if="isMod">
              <span style="display: block;height:38px;width:178px;">{{ memberInfo.mobile }}</span><el-button type="text" v-text="mobileMod" @click="open"/>
            </span>
            <span v-else v-text="member.mobile"></span>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <span v-if="isMod">
              <el-input-number
                v-model="memberInfo.age"
                controls-position="right"
                :min="0"
                :max="200"
              />
            </span>
            <span v-else>
              <span v-if="member.age !== undefined && member.age !== ''" v-text="Number(member.age)+'岁'"/>
              <span v-else v-text="0+'岁'"/>
            </span>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <span v-if="isMod">
              <el-switch
                v-model="memberInfo.sex"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="男"
                inactive-text="女"
                :active-value="0"
                :inactive-value="1" />
            </span>
            <span v-else>
              <span v-if="member.sex==0" v-text="'男'"/>
              <span v-else-if="member.sex==1" v-text="'女'"/>
              <span v-else v-text="'未知'"/>
            </span>
          </el-form-item>
          <el-form-item label="签名" prop="email">
            <!-- <el-input v-model="memberInfo.sign"></el-input> -->
            <span v-if="isMod">
              <el-input
                v-if="isMod"
                type="textarea"
                :rows="2"
                resize="none"
                placeholder="请输入内容"
                v-model="memberInfo.sign"
                maxlength="30"
                :show-word-limit="true" />
            </span>
            <span v-else>
              <textarea disabled autocomplete="off" rows="2" maxlength="30" class="el-textarea__inner" style="resize: none; min-height: 32.995px; border: 0;" v-if="member.sign === ''||member.sign==null" v-text="'这个人很神秘，还没有什么签名....'"/>
              <textarea disabled autocomplete="off" rows="2" maxlength="30" class="el-textarea__inner" style="resize: none; min-height: 32.995px; border: 0;" v-else v-text="member.sign"/>
            </span>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :modal="true"
      :append-to-body='true'
      center>
      <el-form :model="changeMobile" ref="form" :rules="changeMobileRules" label-width="100px" :hide-required-asterisk="true">
        <!-- 验证码 -->
        <el-form-item>
          <el-input :disabled="true" v-model="member.mobile" placeholder="原手机号"></el-input>
        </el-form-item>
        <el-form-item prop="mobile">
          <el-input v-model="changeMobile.mobile" placeholder="新手机号"></el-input>
        </el-form-item>
        <el-form-item prop="verify">
          <div class="bind_code">
            <el-input
              class="bind_code_input code"
              v-model="changeMobile.code"
              type="text"
              placeholder="验证码"
            />
            <el-button
              type="text"
              @click.native.prevent="sendCode"
              class="codebtn"
              :disabled="isMobileDisabled"
              v-text="btnText"
              />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changePhoneMethod">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { userInfo, updateUser } from "@/api/user.js";
import member from "@/api/member"
import register from "@/api/register"
import cookie from "js-cookie"

export default {
  data() {
    let validatePhone = (rule,value,callback)=>{
      if (!value){
        this.isMobileDisabled = true
        callback(new Error('手机号不能为空！'))
        return;
      }
      //使用正则表达式进行验证手机号码
      if ((!/^1[3456789]\d{9}$/.test(value))){
        this.isMobileDisabled = true
        callback(new Error('手机号格式不正确！'))
        return;
      }
      this.isMobileDisabled = false
    }
    return {
      btnText: "获取验证码",
      dialogVisible: false,
      memberId: null,
      member: {
        id: "",
        mobile: "",
        password: "",
        nickname: "",
        sex: null,
        age: null,
        avatar: "",
        sign: null
      },
      second: 60,
      memberInfo: {},
      isMod: false,
      functionTitle: "个人简介",
      rules: {
        nickname: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ]
      },
      changeMobileRules: {
        mobile: [
          { required: true, validator: validatePhone, trigger: "blur" },
        ],
      },
      changeMobile: {
        id: '',
        oldMobile: '',
        mobile: '',
        code: ''
      },
      isMobileMod: false,
      isMobileDisabled: true,
      mobileMod: '更改手机号'
    };
  },
  created() {
    this.token = cookie.get("user_token");
    const jsonStr = cookie.get("user_ucenter");
    if (this.$route.params.id !== undefined) {
      this.memberId = this.$route.params.id;
      this.load();
    } else if (jsonStr) {
      this.member = JSON.parse(jsonStr);
      this.memberId = this.member.id;
      this.load();
    }
    this.memberInfo = this.member
  },
  mounted() {},
  methods: {
    load() {
      member
        .getMemberInfoById(this.memberId)
        .then((res) => {
          this.member = res.data.data.member;
          this.memberInfo = this.member
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submit() {
      member.updateMemberInfo(this.memberInfo)
        .then((res) => {
          const result = res.data;
          if (result.success) {
            this.$message({
              message: "修改个人信息成功！",
              type: "success",
            })
            this.$router.push({ name:'me-personinfo', params: {id: this.member.id,date: new Date().getTime()}})
          } else {
            this.$message.error("修改个人信息失败！");
            console.log(result.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleClose() {
      this.dialogVisible = false;
      this.$emit("flesh");
    },
    handleAvatarSuccess(res, file) {
      this.memberInfo.avatar = res.data.url
      this.$message({
          message: '上传成功！',
          type: 'success'
        })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    open() {
      this.dialogVisible = true
      this.changeMobile.id = this.member.id
      this.changeMobile.oldMobile = this.member.mobile
    },
    sendCode() {
      register.getChangeMobile(this.changeMobile.oldMobile)
        .then(response => {
          if (response.data.success) {
            this.$message({
              message: '验证码发送成功！',
              type: 'success'
            })
          this.timeDown()
          }
        })
    },
    timeDown() {
      let result = setInterval(() => {
        --this.second;
        this.btnText = this.second
        this.isMobileDisabled = true;
        if (this.second < 1) {
          clearInterval(result);
          this.sending = true;
          this.isMobileDisabled = false;
          this.second = 60;
          this.btnText = "获取验证码"
        }
      }, 1000);        
    },
    modInfo() {
      this.isMod = true
      this.memberInfo = this.member
    },
    changePhoneMethod() {
      register.changePhone(this.changeMobile)
        .then(resp => {
          const result = resp.data
          if (result.success) {
            this.dialogVisible = false
            this.$message({
              message: '更换手机号成功！',
              type: 'success'
            })
            this.load()
          } else {
            this.$message.error(result.message)
          }
        })
    }
  },
};
</script>

<style scope>
.updateinfo {
  /* height: 350px; */
  overflow: auto;
  
}
.update-form {
  /* width: 330px; */
  /* float: left; */
  width: 60%;
  height: 100%;
  margin: 0 auto;
  margin-top: 20px;
}
.personalInfo-header {
  width: 100%;
  height: 50px;
  position: relative;
  border-bottom: 1px solid rgb(204, 208, 224);
}
.operat-box {
  position: absolute;
  right: 10px;
  top: 5px;
}
.function-title {
  position: absolute;
  left: 30px;
  font-size: 16px;
  font-weight: 600;
  line-height: 50px;
}
.el-input {
  width: 178px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
  .el-form-item {
    margin-bottom: 12px;
  }
  .codebtn {
    position: absolute;
    top: 0px;
    right: 140px;
    font-size: 11px;
    font-weight: 500;
    font-family: PingFang SC-Medium, PingFang SC;
    color: #409EFF;
    line-height: 15px;
    cursor: pointer;
    padding-left: 10px;
  }
</style>
